<!DOCTYPE html>
<html class='objectContainer'>
    <head>
        <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
        <title>Progress Bars</title>
        <link rel="stylesheet" href="stylesheets/stylesheet.css">

        <script src="angular.min.js"></script>
        <script src="classes/progressBar.js"></script>
        <script src="classes/globalButtons.js"></script>
        <script src="classes/helpers.js"></script>
        <script src="classes/graphics.js"></script>
        <script src="classes/handleSaving.js"></script>
    </head>
    <body data-ng-app="myApp" ng-controller="myCtrl" class='objectContainer' style='text-align:center;position:absolute;background-color:#c1d7ee;font-family:Arial, Helvetica, serif;'>
        <div data-ng-click="isProgressStopped = (!isProgressStopped)" class='hyperVisible quickButton ' style='width:120px;'>Toggle Progress Movement Visibility</div>
        <div data-ng-click="hideRows = (!hideRows)" class='hyperVisible quickButton' style="width:102px;">Toggle Progress Visible</div>
        <!--<div ng-click="" class='hyperVisible quickButton'>Toggle Row Visible</div>
        <div ng-click="" class='hyperVisible quickButton'>Toggle Exp Visible</div>-->
        <div data-ng-click="toggledBarsLeft=!toggledBarsLeft" class='hyperVisible quickButton'>Toggle Bar Direction</div>
        <div id='fps' style='float:left;font-size:14px;background-color:grey;width:60px;padding:3px;border-radius:5px;'>{{fps}} fps</div>
        
        <div id='progressBars' style='margin-top:10px;display:block;width:50%' ng-show="!hideRows" class='objectContainer'></div>
        <div id='buttons' class='objectContainer'></div>

        <div style='width:100%;font-size: 14px;margin-top:10px;text-align:center;'>
            To mass-buy, click a button then hold Enter<br>
            1% of current resources will transfer to the next progress bar upon completion<br>
            Level 2 gives +5% speed, 3 gives +6%, 4 gives +7%, 5 gives +8%, etc.<br>
            If speed is high enough, visible speed is reduced by 10, but all gains are unchanged.<br>
            There is full saving every few seconds, and the game works 100% in a different tab.<br>
            Use the arrow keys and Enter (or WASD and Space) to buy upgrades.<br>
        </div>
        <!--<div style='text-align:left;font-size:12px;width:100%;margin-top:30px;margin-left:10px;margin-bottom:10px;color:grey'>If you want patterns, not gameplay (won't be in final version):</div>-->
        <!--<div data-ng-click="testSettings()" style='float:left;width:75px' class='hyperVisible quickButton '>+1k</div>-->
        <!--<div data-ng-click="testSettings2()" style='float:left;width:75px' class='hyperVisible quickButton '>+50k </div>-->
        <div data-ng-click="clearSave()" style='float:left;width:75px' class='hyperVisible quickButton '>Clear Save</div>
        <div data-ng-click="toggleStartStop()" class='hyperVisible quickButton ' style="float:left;">Toggle Start / Stop (for debug)</div>
    </body>
</html>

<script>
//the answer to "how to i access scope variables from console"
//angular.element($0).scope()

/* TODO: 
speed to the left
level inside 
produces currencies[row]
spawns with a buy button on row+1 (further down) that costs  5 * Math.pow(3, (length - row)) of currencies[row], and gives +1 to expGain of row+1

upgrades come from the rows 3 rows up, where a x2 to 7 is available for 10k of rows 4 and 1
each row gains expGain into Level
Level up gives 10% higher expGain bonus
levelUp needs 10 exp to start, 
*/


var multFromFps = 1;
var initialRowCount = 4;
var msWaitTime = 50;
var timeList = [];
var timer = 0;
var timeUntilNextBar = -500; //so that it makes the first row immediately
var timeUntilNextSave = 0;
var stop = 0;
var selectedButton = [-1, 0];
var myKeyQueue = [];


var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval, $compile) {

    $scope.tick = function() {
        if(stop) {
            return;
        }
        timer++;
        handleFPSDifference();

        $scope.updateProgressForAllRows();

        //manual addition to give starting rows
        if(($scope.pbars.length < initialRowCount) && (timer - timeUntilNextBar >= 25)) {
            $scope.addProgressBar();
            timeUntilNextBar = timer;
        }
        if(timer - timeUntilNextSave >= 300) {
            saveGame.saveTheGame();
            timeUntilNextSave = timer;
        }
    };

    $scope.updateProgressForAllRows = function() {
        for(var lx = 0; lx < $scope.pbars.length; lx++) {
            $scope.updateRowProgress(lx)
        }
    };

    $scope.updateRowProgress = function(row) { //main game progress
        $scope.pbars[row].nextProgressDown((1+$scope.boughtSpeedBonus/100), function() {
            var lastIndex = $scope.pbars.length-1;

            $scope.pbars[row].nextExp($scope.secondsLevelBoost);
            var resourceGain = $scope.pbars[row].calcTotalResGain();
            $scope.pbars[row].resGainOpacity = 1;
            $scope.pbars[row].resources += resourceGain;
            $scope.pbars[row].tempResGain = resourceGain;
            if(row < lastIndex) { //all but the bottom-most row
                var onePercentGrid = [.01, 0.0956179249911957, 0.6339676587267711, 0.9999568287525893, 1,1,1,1,1,1,1,1,1,1,1,1];
                var onePercent = Math.floor($scope.pbars[row].resources * onePercentGrid[$scope.pbars[row].speedReduceMult-1] * 10)/10;
                //console.log(onePercent);
                $scope.pbars[row+1].resGainOpacity = 1;
                $scope.pbars[row+1].tempResGain = onePercent;
                $scope.pbars[row+1].resources += onePercent;
                $scope.pbars[row].resources -= onePercent;
                $scope.pbars[row].tempResGain = (resourceGain - onePercent);

                $scope.pbars[row+1].handleResourceChange();

                //$scope.pbars[row+1].speedGain = 1 * Math.pow(10, $scope.pbars[row].speedReduceMult-1); //($scope.pbars[row].level) * .05
                //$scope.pbars[row+1].speedMult = $scope.pbars[row+1].speedGain + $scope.pbars[row+1].speedMult;
            }
            $scope.pbars[row].handleResourceChange();
        });
    };

    //----------------Don't bother looking----------------
    {
        function changeSelected(newSelected) {
            if(!$scope.pbars[selectedButton[0]]) {
                return;
            }
            $scope.pbars[selectedButton[0]].changeSelect(-1);
            selectedButton = newSelected;
            if($scope.pbars[selectedButton[0]]) {
                $scope.pbars[selectedButton[0]].changeSelect(selectedButton[1]);
            }
        }
        document.addEventListener("keydown", function(e) {
            var code = (e.charCode !== 0 ? e.charCode : e.keyCode);
            myKeyQueue.push(code);
            processKeyQueue();
        });

        function processKeyQueue() {
            var key = myKeyQueue[0];
            myKeyQueue.splice(0, 1);
            if(key === 13 || key === 32) { //enter
                $scope.pbars[selectedButton[0]].clickButtonByColumn(selectedButton[1]);
            }
            if(!$scope.pbars[selectedButton[0]]) {
                selectedButton[0] = $scope.pbars.length-1;
                return;
            }
            if(key === 38 || key === 87) { //up
                if(selectedButton[0] < 1) {
                    selectedButton[0] = 1;
                }
                $scope.pbars[selectedButton[0]].changeSelect(-1);
                selectedButton[0]--;
                $scope.pbars[selectedButton[0]].changeSelect(selectedButton[1]);
            }
            if(key === 40 || key === 83) { //down
                if(selectedButton[0] > $scope.pbars.length-2) {
                    selectedButton[0] = $scope.pbars.length-2;
                }
                $scope.pbars[selectedButton[0]].changeSelect(-1);
                selectedButton[0]++;
                $scope.pbars[selectedButton[0]].changeSelect(selectedButton[1]);
            }
            if(key === 37 || key === 65) { //left / a
                if(selectedButton[1] < 1) {
                    selectedButton[1] = 1;
                }
                $scope.pbars[selectedButton[0]].changeSelect(-1);
                selectedButton[1]--;
                $scope.pbars[selectedButton[0]].changeSelect(selectedButton[1]);
            }
            if(key === 39 || key === 68) { //right
                if(selectedButton[1] > $scope.pbars[selectedButton[0]].isSelected.length-2) {
                    selectedButton[1] = $scope.pbars[selectedButton[0]].isSelected.length-2;
                }
                $scope.pbars[selectedButton[0]].changeSelect(-1);
                selectedButton[1]++;
                $scope.pbars[selectedButton[0]].changeSelect(selectedButton[1]);
            }
//            if(myKeyQueue.length > 0) {
//                $scope.pbars[selectedButton[0]].changeSelect(selectedButton[1]);
//            }
        }

        var keys = {32: 1, 37: 1, 38: 1, 39: 1, 40: 1};

        function preventDefault(e) {
            e = e || window.event;
            if (e.preventDefault)
                e.preventDefault();
            e.returnValue = false;
        }

        function preventDefaultForScrollKeys(e) {
            if (keys[e.keyCode]) {
                preventDefault(e);
                return false;
            }
        }

        function disableScroll() {
            document.onkeydown  = preventDefaultForScrollKeys;
        }
        disableScroll();

        function enableScroll() {
            if (window.removeEventListener)
                window.removeEventListener('DOMMouseScroll', preventDefault, false);
            document.onkeydown = null;
        }

        $scope.intToString = intToString;
        $scope.intToStringRound = intToStringRound;
        $scope.intToStringNegative = intToStringNegative;
        $scope.round1 = round1;
        var graphics = new Graphics($scope);
        $scope.addProgressBarUI = function () {
            var newDiv = angular.element(graphics.createProgressBarUI($scope.pbars.length - 1));
            var progressBarContainer = document.getElementById('progressBars');
            angular.element(progressBarContainer).append(newDiv);
            $compile(newDiv)($scope);
        };
        $scope.addBuyButtonTemplate = function (buttonText, topNumVarName, topNumColor,
                                                onClickFunctionName, costVarName, botNumColor) {
            var newDiv = angular.element(graphics.createButton(buttonText, topNumVarName, topNumColor,
                onClickFunctionName, costVarName, botNumColor));
            var progressBarContainer = document.getElementById('buttons');
            angular.element(progressBarContainer).append(newDiv);
            $compile(newDiv)($scope);
        };

        $scope.addProgressBar = function () { //add progress bar (both data and UI)
            $scope.addProgressBarData();
            $scope.addProgressBarUI();
        };

        $scope.toggleStartStop = function () {
            stop = !stop;
            timeList = [];
        };

        function handleFPSDifference() {
            timeList.push(new Date().getTime());
            if(timeList.length > 100) {
                timeList.splice(0, 1);
                var fps = msWaitTime/((timeList[timeList.length-1] - timeList[0]) / (timeList.length-1))*100;
                multFromFps = 100/fps;
                $scope.fps = round(fps)+"%";
            } else {
                multFromFps = 1;
                $scope.fps = "...";
            }
        }

        var doWork = new Worker('interval.js');
        doWork.onmessage = function (event) {
            if (event.data === 'interval.start') {
                $scope.$apply($scope.tick());
            }
        };
        doWork.postMessage({start: true, ms: msWaitTime});

        var saveGame = new SaveGame($scope);
        saveGame.loadTheGame();
        $scope.clearSave = saveGame.loadDefaults;
    }

    //Initial conditions
    $scope.addBuyButtonTemplate("+5% Global Speed Increase", "boughtSpeedBonus", "blue", "buySpeedBonus", "costSpeedBonus", "white");
    $scope.addBuyButtonTemplate("Seconds of Boost on Level Up +1", "secondsLevelBoost", "blue","buySecondsBoost", "costSecondsBoost", "white");
    $scope.addBuyButtonTemplate("Buy 2 Progress Bars", "pbars.length", "blue", "buyProgressBar", "costBuyRow", "white");
//    $scope.addBuyButtonTemplate("Gain for Last", "pbars[pbars.length-1].resGain", "blue", "buyGainFirst", "costGainFirst", "white");
    $scope.addBuyButtonTemplate("Gain for All +1", "gainAll", "blue", "buyGainAll", "costGainAll", "white");
    $scope.addBuyButtonTemplate("Exp Gain +1", "expMult", "blue", "buyExpMult", "costExpMult", "white");

    var buttons = new GlobalButtons($scope);
    $scope.buySpeedBonus = buttons.buySpeedBonus;
    $scope.buySecondsBoost = buttons.buySecondsBoost;
    $scope.buyProgressBar = buttons.buyProgressBar;
    $scope.buyGainFirst = buttons.buyGainFirst;
    $scope.buyGainAll = buttons.buyGainAll;
    $scope.buyExpMult = buttons.buyExpMult;

    $scope.buttonMouseOver = buttons.buttonMouseOver;
    $scope.buttonMouseLeave = buttons.buttonMouseLeave;

    $scope.testSettings = buttons.testSettings;
    $scope.testSettings2 = buttons.testSettings2;

    $scope.addProgressBarData = function(type) {
        //progressBar (initialProgressReq, initialProgress, gainAmount, row) {
        $scope.pbars.unshift(new ProgressBar ($scope, 20, 20, $scope.gainAll, $scope.pbars.length));
        changeSelected([selectedButton[0]+1, selectedButton[1]]);
    };

});

</script>